
import { useMount } from '@/hooks'
import { useAppSelector } from '@/store/hooks'
import { TreasuryPrize, TreasuryPrizeOwnerType, TreasuryPrizeOpenMode, TreasuryPrizeStatus, TreasuryPrizeWinMode, TreasuryRole } from '@/types'
import { CdnImage, Form, PrimaryButton, TextItem } from '@/ui-components'
import Card from '@/ui-components/card'
import { Text, View } from '@tarojs/components'
import to from 'await-to-js'
import dayjs from 'dayjs'
import { useMemo, useState } from 'react'
import Taro from '@tarojs/taro'
import { getTreasuryPrizeDetail, joinTreasuryPrize } from '../../network'
import { UserTreasury } from '@/store/treasurySlice'
import { dialog } from '@/utils'


const TreasuryPrizeStatusItem = ({ treasuryPrize } : { treasuryPrize: TreasuryPrize }) => {
  if (treasuryPrize.status === TreasuryPrizeStatus.complete) {
    return <TextItem
      label='开奖状态'
      renderRight={() => <Text className='warning'>已开奖</Text>}
    />
  }
  if (treasuryPrize.status === TreasuryPrizeStatus.frozen) {
    return <TextItem
      label='开奖状态'
      renderRight={() => <Text className='fail'>冻结</Text>}
    />
  }
  if (treasuryPrize.openMode === TreasuryPrizeOpenMode.person) {
    return <TextItem
      label='开奖状态'
      renderRight={() => <View>满<Text className='warning'>{treasuryPrize.personNum}</Text>人开奖</View>}
    />
  }
  if (treasuryPrize.openMode === TreasuryPrizeOpenMode.time) {
    return <TextItem
      label='开奖状态'
      renderRight={() => <View><Text className='warning'>{dayjs(treasuryPrize.openTime).format('YYYY/MM/DD HH:mm:ss')}</Text>开奖</View>}
    />
  }
}

const TreasuryPrizeWinModeItem = ({ treasuryPrize } : { treasuryPrize: TreasuryPrize }) => {
  if (treasuryPrize.winMode === TreasuryPrizeWinMode.person) {
    return <TextItem
      label='中奖人数'
      value={`${treasuryPrize.winNum}人`}
    />
  }
  if (treasuryPrize.winMode === TreasuryPrizeWinMode.rate) {
    return <TextItem
      label='中奖概率'
      renderRight={() => <View>中奖率<Text className='warning'>{treasuryPrize.winRate}%</Text></View>}
    />
  }
}


const onPressNext = async (treasuryPrize: TreasuryPrize, userTreasury: UserTreasury) => {
  if (treasuryPrize.cost > userTreasury.userScore) {
    Taro.showToast({ title: '积分不足，无法参与抽奖', icon: 'none', duration: 2000 })
    return
  }
const [err] = await to(joinTreasuryPrize(treasuryPrize.treasuryPrizeId))
  if (err) {
    Taro.showToast({ title: '参与抽奖失败', icon: 'none', duration: 2000  })
  } else {
    Taro.showToast({ title: '参与抽奖成功', icon: 'success', duration: 2000  })
    Taro.navigateBack()
  }
}

export default function TreasuryPrizeDetailPage() {

  const [ treasuryPrize, setTreasuryPrize ] = useState<TreasuryPrize | undefined >(undefined)
  const userTreasury = useAppSelector(state => state.treasury.userTreasury)

  const treasuryPrizeId = useMemo(() => {
    return Number(Taro.getCurrentInstance().router?.params.treasuryPrizeId)
  }, [])

  useMount(async () => {
    const [err, treasuryPrize] = await to(getTreasuryPrizeDetail(treasuryPrizeId))
    if (err) return
    setTreasuryPrize(treasuryPrize)
  })

  if (treasuryPrize) {
    return (
      <View className='treasury-prize-detail safe-bottom'>
        <Card>
          <View className='p-normal row-start-stretch'>
            <CdnImage src={treasuryPrize.image} className='image-160 border-radius-small' />
            <View className='column-between-start flex-1 ml-medium'>
              <View className='text-title'>{treasuryPrize.name}</View>
              <View className='text-normal'>{treasuryPrize.description}</View>
            </View>
          </View>
          <Form>
            <TextItem label='抽奖发起人' value={treasuryPrize.ownerType === TreasuryPrizeOwnerType.personal ? treasuryPrize.createUserName : '宝库'} />
            <TextItem
              label='奖品价值'
              renderRight={() => <View><Text className='success'>{treasuryPrize.worth}</Text>积分</View>}
            />
            <TextItem
              label='抽奖消耗'
              renderRight={() => <View><Text className='success'>{treasuryPrize.cost}</Text>积分</View>}
            />
            <TextItem
              label='我的积分'
              value={userTreasury.userScore}
            />
            <TreasuryPrizeStatusItem treasuryPrize={treasuryPrize} />
            <TreasuryPrizeWinModeItem treasuryPrize={treasuryPrize} />
            <TextItem
              label='参与人数'
              value={`${treasuryPrize.curNum}人`}
            />
          </Form>
        </Card>
        {
          [TreasuryRole.admin, TreasuryRole.owner].includes(userTreasury.treasuryRole) ? <Card>
            <View className='pv-normal row-aroud-center prize-operation'>
              <View className='column-start-center'>
                <CdnImage src='/common/prize/prize-copy.png' className='image-48' />
                <View className='text-center text-primary mt-normal'>复制抽奖</View>
              </View>
              <View className='line' />
              <View className='column-start-center'>
                <CdnImage src='/common/prize/prize-delete.png' className='image-48' />
                <View className='text-center text-primary mt-normal'>抽奖作废</View>
              </View>
              <View className='line' />
              <View className='column-start-center'>
                <CdnImage src='/common/prize/prize-open.png' className='image-48' />
                <View className='text-center text-primary mt-normal'>立即开奖</View>
              </View>
            </View>
          </Card> : null
        }
        <PrimaryButton
          text='参与抽奖'
          onClick={() => onPressNext(treasuryPrize, userTreasury)}
        />
      </View>
    )
  }
}
